const MongoClient = require('mongodb').MongoClient
const ObjectID = require('mongodb').ObjectID
const Config = require('./config.js')

class Db {
  // 单例模式
  static getInstance() {
    if (!Db.instance) {
      Db.instance = new Db()
    }
    return Db.instance
  }

  constructor() {
    this.dbClient = ''
    this.connect()
  }

  connect() {
    return new Promise((resolve, reject) => {
      if (!this.dbClient) {
        MongoClient.connect(Config.dbUrl, { useUnifiedTopology: true }, (err, client) => {
          if (err) {
            reject(err)
          } else {
            const db = client.db(Config.dbName)
            this.dbClient = db
            resolve(this.dbClient)
          }
        })
      } else {
        resolve(this.dbClient)
      }
    })
  }

  find(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then(function (db) {
        const result = db.collection(collectionName).find(json)
        result.toArray(function (err, docs) {
          if (err) {
            reject(err)
            return
          } else {
            resolve(docs)
          }
        })
      })
    })
  }

  update(collectionName, json1, json2) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).updateOne(json1, {
          $set: json2
        }, (err, result) => {
          if (err) {
            reject(err)
            return
          } else {
            resolve(result)
          }
        })
      })
    })
  }

  insert(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).insertOne(json, function (err, result) {
          if (err) {
            reject(err)
            return
          } else {
            resolve(result)
          }
        })
      })
    })
  }

  remove(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).removeOne(json, function (err, result) {
          if (err) {
            reject(err)
            return
          } else {
            resolve(result)
          }
        })
      })
    })
  }

  // 查询 _id
  getObjectID(id) {
    return new ObjectID(id)
  }
}

module.exports = Db.getInstance()
